<?php

namespace App\Http\Controllers\Admin\SystemSet;

use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;

//引用http请求类
use App\Exceptions\BasicException;

//引入框架异常处理类
use Illuminate\Support\Facades\Hash;

//引入hash
use App\Services\Cache\AdminCacheService;

//admin缓存
use App\Services\Tools\JwtService;

//引入JWT服务
use App\Services\Tools\FileService;

//引入文件处理类
use App\Response\Response;

class AdminController extends BaseController
{

    /**
     * @api {post} /system-set/admin 管理员-添加
     * @apiVersion 0.1.0
     * @apiName 管理员添加
     * @apiGroup 系统设置
     * @apiParam {string} admin_name 管理员账号,英文(最大60字符),必传
     * @apiParam {string} password md5加密后的密码32位,必传
     * @apiParam {string} phone_number 电话号码必传,必传
     * @apiParam {string} confirm_password 确认md5加密后的密码32位,必传
     * @apiParam {number} role_id 角色编号(查询当前公会下的角色),0：超级管理员，其它根据接口，必传
     * @apiParam {string} email 邮箱,可选
     * @apiParam {string} realname 管理员真实姓名,可选
     * @apiParam {number} status 是否禁用  1正常 2禁用 必传
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 20006 当前账号已存在,请换个账号添加
     * @apiError 20060 该角色不存在
     * @apiError 90007 管理员添加失败(数据库操作失败)
     * @apiErrorExample 错误响应
     *      {
     *          "code": 20050,
     *          "message": "errorMsg"
     *      }
     */
    public function adminAdd(Request $request)
    {
        $param = $request->only('admin_name', 'phone_number', 'email', 'realname', 'role_id', 'status');
        $v = app('validator')->make($param,[
            'admin_name'       => 'required|string|min:1|max:50',
            'phone_number'     => 'required|regex:/^1[345789][0-9]{9}$/',
            'email'            => 'filled|email',
            'realname'         => 'filled|string',
            'role_id'          => 'required|integer|min:0',
            'status'           => 'required|numeric|in:1,2',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        //校验admin_account是否存在
        $admin = app('repo_admin')->admin_detail($param['admin_name'], 'admin_name');
        if ($admin) {
            throw new BasicException(20006);
        }

        $phone = app('repo_admin')->admin_detail($param['phone_number'], 'phone_number');
        if ($phone) {
            throw new BasicException(20011);
        }

        if ($param['role_id'] > 0) {
            $exist = app('model_role')->isExist($param['role_id']);
            if (!$exist) throw new BasicException(0, '角色id错误');
        }

        //数据组合
        $param['email'] = !empty($param['email']) ? $param['email'] : '';
        $param['realname'] = !empty($param['realname']) ? $param['realname'] : '';
        $param['disabled'] = $param['status'] == 1 ? 1 : 0;
        $param['addtime'] = time();

        //执行添加操作
        app('repo_admin')->adminAdd($param);

        return Response::sendData(true);
    }

    /**
     * @api {get} /system-set/admin 管理员-列表
     * @apiVersion 0.1.0
     * @apiName 管理员列表
     * @apiGroup 系统设置
     * @apiParam {string} search 要搜索的内容,可选
     * @apiSuccessExample 成功响应
     *{
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "admin_id(管理员账号)": 33,
     * "admin_name(管理员账号)": "zhangsan",
     * "realname(管理员姓名)": "张三",
     * "email(邮箱)": "",
     * "status(状态1正常2封禁)": 1,
     * "add_time(注册时间)": "2020-07-28 14:46:55",
     * "last_login_time(最后一次登录时间)": "1970-01-01 08:00:00",
     * "last_login_ip(最后一次登录IP)": "0.0.0.0",
     *  "phone_number" (电话号码):6656165164
     * "login_count(累计登录次数)": 0,
     * "role(管理员角色)": "超级管理员",
     * "role_id(管理员角色id)": 15
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": 10,
     * "next": null,
     * "total": 2
     * }
     * }
     * }
     */
    public function adminList(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'perPage' => 'filled|numeric',
                'page'    => 'filled|numeric',
                'keyword' => 'filled|string',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }

        $page = $request->input('page', 1);
        $perPage = $request->input('perPage', 10);
        $param = $request->only(['keyword']);

        $list = app('repo_admin')->adminList($param, $page, $perPage);

        return Response::sendList($list);
    }

    /**
     * @api {put} /system-set/admin 管理员-编辑
     * @apiVersion 0.1.0
     * @apiName 管理员-编辑
     * @apiGroup 系统设置
     * @apiParam {string} password md5加密后的密码32位,可选
     * @apiParam {string} confirm_password 确认md5加密后的密码32位,可选
     * @apiParam {string} phone_number 电话号码必传,必传
     * @apiParam {number} role_id 角色编号(查询当前公会下的角色),0：超级管理员，其它根据接口，必传
     * @apiParam {string} email 邮箱,可选
     * @apiParam {string} realname 管理员真实姓名,可选
     * @apiParam {number} status 是否禁用  1正常 2禁用 必传
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 20008 管理员编辑失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 20050,
     *          "message": "errorMsg"
     *      }
     */
    public function adminEdit(Request $request)
    {
        $param = $request->only('id', 'phone_number', 'email', 'realname', 'role_id', 'status');
        $v = app('validator')->make($param,[
            'id'         => 'required|integer',
            'phone_number'     => 'required|regex:/^1[345789][0-9]{9}$/',
            'email'            => 'filled|email',
            'realname'         => 'filled|string',
            'role_id'          => 'required|integer|min:0',
            'status'           => 'required|numeric|in:1,2',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $id = $param['id'];

        if ($param['role_id'] > 0) {
            $exist = app('model_role')->isExist($param['role_id']);
            if (!$exist) throw new BasicException(0, '角色id错误');
        }

        $param['disabled'] = $param['status'] == 1 ? 1 : 0;

        $phone = app('repo_admin')->admin_detail($param['phone_number'], 'phone_number');
        if ($phone && $phone->admin_id != $id) {
            throw new BasicException(20011);
        }

        unset($param['id']);
        app('repo_admin')->editAdmin($id, $param);

        return Response::sendData(true);
    }

    /**
     * @api {delete} /system-set/admin 管理员-删除参数
     * @apiVersion 0.1.0
     * @apiName 系统设置-管理员-删除参数
     * @apiGroup 系统设置
     * @apiParam {string} ids                       字符串分割的id 必传
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function adminDelete(Request $request)
    {
        $param = $request->input();
        $v = app('validator')->make($param,[
            'ids' => 'required|string',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $idsStr = $request->input("ids");
        $idsArr = explode(",", $idsStr);

        $rows = app('repo_admin')->delAdmin($idsArr);
        if (!$rows) {
            throw new BasicException(10001, "删除失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {get} /system-set/self/info 自己的管理员信息
     * @apiVersion 0.1.0
     * @apiName 自己的管理员信息
     * @apiGroup 系统设置
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "admin_name": "xsc",//账号
     * "email": "1112312312@qq.com",//邮箱
     * "phone_number": "15279831247",
     * "realname": "xiao1",//真实姓名
     * "avatar": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/android_images/547176/20191112181028_1573553427997743.jpg"//头像
     * }
     * }
     */
    public function selfAdminInfo(Request $request)
    {
        $res = app('model_admin')->where('admin_id', $request->admin_id)->first();


        $rdata = [
            'admin_name'   => $res['admin_name'],
            'email'        => $res['email'],
            'phone_number' => $res['phone_number'],
            'realname'     => $res['realname'],
            'avatar'       => empty($res->avatar) ? $res->avatar : env('YUTANG_ADMINI_AVATAR'),
        ];

        return Response::sendData($rdata);
    }

    /**
     * @api {put} /system-set/self/info 修改自己的管理员信息
     * @apiVersion 0.1.0
     * @apiName 修改自己的管理员信息
     * @apiGroup 系统设置
     * @apiParam {string} password md5加密后的密码32位,可选
     * @apiParam {string} confirm_password 确认md5加密后的密码32位,可选
     * @apiParam {string} phone_number 电话号码 可选
     * @apiParam {string} email 邮箱,可选
     * @apiParam {string} avatar 头像地址 可选
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "admin_name": "xsc",//账号
     * "email": "1112312312@qq.com",//邮箱
     * "phone_number": "15279831247",
     * "realname": "xiao1",//真实姓名
     * "avatar": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/android_images/547176/20191112181028_1573553427997743.jpg"//头像
     * }
     * }
     */
    public function setSelfInfo(Request $request)
    {
        $param = $request->input();
        $v = app('validator')->make($param,[
            'password'         => 'filled|string|size:32',
            'confirm_password' => 'filled|string|size:32',
            'phone_number'     => 'filled|regex:/^1[345789][0-9]{9}$/',
            'email'            => 'filled|email',
            'avatar'           => 'filled|string|max:255',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $param = $request->only(['password', 'confirm_password', 'phone_number', 'email', 'avatar']);
        if (isset($param['password']) && !isset($param['confirm_password'])) {
            throw new BasicException(10001, "请确认密码！");
        }

        if (!isset($param['password']) && isset($param['confirm_password'])) {
            throw new BasicException(10001, "请输入密码！");
        }
        if (isset($param['password']) && isset($param['confirm_password'])) {
            if ($param['password'] != $param['confirm_password']) {
                throw new BasicException(10001, "两次输入的密码不一致！");
            }
            $param['new_password'] = Hash::make($param['password']);
        }
        unset($param['password']);
        unset($param['confirm_password']);

        if (isset($param['phone_number'])) {
            $phone = app('repo_admin')->admin_detail($param['phone_number'], 'phone_number');
            if ($phone && $phone->admin_id != $request->admin_id) {
                throw new BasicException(20011);
            }
        }

        if (empty($param)) {
            throw new BasicException(10001, '至少填一个参数');
        }
        $res = app('repo_admin')->editAdmin($request->admin_id, $param);
        if (!$res) {
            throw new BasicException(20011);
        }

        return Response::sendData(1);
    }

    /**
     * @api {get} /system-set/admin/operation-log 管理员操作日志列表
     * @apiVersion 0.1.0
     * @apiGroup 系统设置
     *
     * @apiParam {int} admin_id 管理员id
     * @apiParam {string} uri 路由地址
     * @apiParam {string} method 请求方式
     * @apiParam {string} created_time_start 创建时间开始
     * @apiParam {string} created_time_end 创建时间结束
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 15623, 日志id
    "admin_id": 1,
    "client_ip": "127.0.0.1", 访问的ip
    "uri": "access/admin/select-list", 访问的路由
    "method": "get", 请求方式
    "content": { 请求参数：
    "action_name": "管理员下拉框"
    },
    "created_at": "2021-11-09 20:36:01", 创建时间
    "admin": { 请求的管理员信息：
    "id": 1,
    "name": "许龙彪", 管理员名字
    "phone_number": "15990164751", 管理员手机号
    }
    }
    ],
    "first_page_url": "http://financial/access/admin/operation-log?page=1",
    "from": 1,
    "last_page": 5116,
    "last_page_url": "http://financial/access/admin/operation-log?page=5116",
    "next_page_url": "http://financial/access/admin/operation-log?page=2",
    "path": "http://financial/access/admin/operation-log",
    "per_page": "1",
    "prev_page_url": null,
    "to": 1,
    "total": 5116
    },
    "message": ""
    }
     */
    public function operationLog(Request $request)
    {
        $param = $request->only(['admin_id', 'uri', 'method', 'created_time_start', 'created_time_end', 'page', 'page_size']);
        $va = app('validator')->make($param, [
            'admin_id' => 'integer|min:1|max:65535',
            'uri' => 'string|max:100',
            'method' => 'string|max:8',
            'created_time_start' => 'date_format:Y-m-d H:i:s',
            'created_time_end' => 'date_format:Y-m-d H:i:s',
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($va->fails()) {
            throw new BasicException(10001, $va->errors()->first());
        }

        $adminId = $params['admin_id'] ?? 0;
        $uri = $params['uri'] ?? '';
        $method = $params['method'] ?? '';
        $createdTimeStart = $params['created_time_start'] ?? '';
        $createdTimeEnd = $params['created_time_end'] ?? '';
        $pageSize = $params['page_size'] ?? 10;

        $where = [];
        if ($adminId > 0) {
            $where[] = ['admin_id', '=', $adminId];
        }
        if ($uri) {
            $where[] = ['uri', '=', $uri];
        }
        if ($method) {
            $where[] = ['method', '=', $method];
        }
        if ($createdTimeStart) {
            $where[] = ['created_at', '>=', $createdTimeStart];
        }
        if ($createdTimeEnd) {
            $where[] = ['created_at', '<=', $createdTimeEnd];
        }

        $list = app('model_admin_log')
            ->where($where)
            ->with(['admin' => function($query) {
                $query->select('admin_id', 'realname', 'phone_number');
            }])
            ->orderByDesc('id')
            ->paginate($pageSize);
        foreach ($list as &$v) {
            $v->content = unserialize($v->content);
        }
        return Response::sendData($list);
    }
}
